// -------------------------------------默认的异步操作------------------------------
export function getDirectory(directoryName, successCB) {
	plus.io.requestFileSystem(
		plus.io.PRIVATE_DOC,
		function(fs) {
			//directoryName:可以是一个文件名，如果是路径，则路径上的所有文件夹都会自动创建
			fs.root.getDirectory(directoryName, {
				create: true
			}, successCB, function() {});
			console.log("创建完成.............")
		},
		function(e) {}
	);
}

export function getFile(filePath, successCB) {
	plus.io.requestFileSystem(
		plus.io.PRIVATE_DOC,
		function(fs) {
			//directoryName:可以是一个文件名，如果是路径，则路径上的所有文件夹都会自动创建
			fs.root.getFile(filePath, {
				create: true
			}, successCB, function() {});
		},
		function(e) {}
	);
}

export async function copyFileToPrivateDoc(sourceFilePath, archivesPath, targetFileName, targetFileType) {
	// 获取源文件的 FileEntry 对象
	return new Promise((resolve, reject) => {
		console.log(plus.io.PRIVATE_DOC);
		console.log('copyFileToPrivateDoc', sourceFilePath);
		// let dir = '/document';
		// let pathUrl = '/document/home:消防每日警情7.22.doc';
		// let environment = plus.android.importClass("android.os.Environment");
		// var sdRoot = environment.getExternalStorageDirectory(); //文件夹根目录
		// var File = plus.android.importClass("java.io.File");
		// var BufferedReader = plus.android.importClass("java.io.BufferedReader");
		// var FileReader = plus.android.importClass("java.io.FileReader");
		// var FileWriter = plus.android.importClass("java.io.FileWriter");
		// console.log(sdRoot + dir)
		// let directory = new File(sdRoot + dir);
		// return
		// '_doc/archiveId_559/images/Screenshot_20231106_113217_uni.UNIF404615.prod.jpg' === sourceFilePath
		plus.io.resolveLocalFileSystemURL(sourceFilePath, async function(entry) {
			try {
				// 获取 "PRIVATE_DOC" 目录的 FileEntry 对象
				const docRootEntry = await getDocRootEntry();
				// 拆分目录路径
				const dirsArray = archivesPath.split('/');
				let currentDirEntry = docRootEntry;
				// 逐级检查和创建目录
				for (let i = 0; i < dirsArray.length; i++) {
					const dirName = dirsArray[i];
					if (!dirName) {
						continue; // 忽略空目录名
					}
					// 检查目录是否存在，如果不存在则创建
					currentDirEntry = await getOrCreateDirectory(currentDirEntry, dirName);
				}
				// 在最终目录下执行文件复制
				let newUrl =
					`${targetFileName.indexOf(targetFileType) > -1 ? targetFileName : targetFileName}`
				let flag = await checkFileExistsInDirectory(currentDirEntry, entry.name)
				if (flag) {
					let file = await getFileAsync(entry.name, currentDirEntry)
					resolve(file)
				} else {
					let res = await copyFileToDirectory(entry, currentDirEntry, newUrl);
					resolve(res)
				}
			} catch (error) {
				console.error('文件操作发生错误: ' + error.message);
				reject(error)
			}
		}, (error) => {
			console.error('copyFileToPrivateDoc')
			reject(error)
		});
	})

}

// 获取 "PRIVATE_DOC" 目录的 FileEntry 对象
export function getDocRootEntry() {
	return new Promise((resolve, reject) => {
		plus.io.resolveLocalFileSystemURL('_doc', resolve, reject);
	});
}

// 检查目录是否存在，如果不存在则创建
export function getOrCreateDirectory(baseDirEntry, dirName) {
	return new Promise((resolve, reject) => {
		baseDirEntry.getDirectory(dirName, {
			create: true
		}, (e) => {
			resolve(e)
		}, reject);
	});
}

// 在目录下执行文件复制
export function copyFileToDirectory(sourceFileEntry, targetDirEntry, targetFileName) {
	return new Promise((resolve, reject) => {
		sourceFileEntry.copyTo(targetDirEntry, targetFileName, (e) => {
			resolve(e)
		}, (error) => {
			console.log(error);
		});
	});
}

export function moveFile(srcFilePath, srcFileName, dstFilePath, dstFileName, successCB) {
	plus.io.resolveLocalFileSystemURL("_documents/b1/bridges.json", function(entry) {
		plus.io.resolveLocalFileSystemURL("_doc/", function(root) {
			entry.moveTo(
				root,
				"bridges12.json",
				function(entry) {},
				function(e) {
					console.log("错误" + JSON.stringify(e));
				}
			);
		})
	})
}

export function copyFile(srcFilePath, srcFileName, dstFilePath, dstFileName, successCB) {
	plus.io.resolveLocalFileSystemURL(srcFilePath + srcFileName, function(entry) {
		plus.io.resolveLocalFileSystemURL("_doc/", function(root) {
			entry.copyTo(
				root,
				srcFileName,
				function(entry) {},
				function(e) {
					console.log("错1误" + JSON.stringify(e));
				}
			);
		})
	})
}

/**
 * 传入目录dirEntry，如果传了fileName，则删除对应文件，否则目录下所有文件全部删除
 * @param {Object} dirEntry
 * @param {Object} fileName
 */
export function removeFile(dirEntry, fileName) {
	plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
		let entry = dirEntry || fs.root;
		let directoryReader = entry.createReader();
		directoryReader.readEntries(function(entries) {
			for (let i = entries.length - 1; i >= 0; i--) {
				if (fileName) {
					if (fileName === entries[i].name) {
						entries[i].remove();
					}
				} else {
					entries[i].remove();
				}
			}
		});
	});
}


// ----------------------------------------------------------------同步化-操作-----------------------------------------
/**
 * 同步化获取文件,文件不存在会自动创建
 * @param {Object} fileName 可以是文件名，也可以是/路径/文件名
 * @param {Object} dirEntry
 * @return 文件Entry
 */
export async function getFileEntryAsync(fileName, dirEntry) {
	return new Promise((resolve) => {
		plus.io.requestFileSystem(
			plus.io.PRIVATE_DOC,
			function(fs) {
				let entry = dirEntry || fs.root;
				entry.getFile(
					fileName, {
						create: true
					},
					function(fileEntry) {
						resolve(fileEntry);
					},
					function(ex) {
						console.log(ex)
					}
				);
			}
		);
	})
}

/**
 * 获取文件夹，不存在会自动创建
 * @param {Object} dirName
 */
export async function getDirEntryAsync(dirName) {
	return new Promise(async (resolve) => {
		plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
			fs.root.getDirectory(dirName, {
				create: true
			}, function(dirEntry) {
				resolve(dirEntry);
			})
		})
	})
}

/**
 * 获取通过fileEntry获取file，不存在会自动创建
 * @param {Object} fileName
 * @param {Object} dirEntry
 */
export async function getFileAsync(fileName, dirEntry) {
	return new Promise(async (resolve) => {
		let fileEntry = await getFileEntryAsync(fileName, dirEntry);
		fileEntry.file(function(file) {
			resolve(file);
		});
	})
}

/**
 * 读取文件中的内容
 * @param {Object} path
 * @param {Object} dirEntry
 */
export async function getFileContextAsync(path, dirEntry) {
	let deffered;
	let fileReader = new plus.io.FileReader();
	fileReader.onloadend = function(evt) {
		deffered(evt.target);
	}
	let file = await getFileAsync(path, dirEntry);
	fileReader.readAsText(file, 'utf-8');
	return new Promise((resolve) => {
		deffered = resolve;
	});
}

/**
 * 向文件中写入数据
 * @param {Object} path 要写入数据的文件的位置
 * @param {Object} fileContext 要写入的内容
 * @param {Object} dirEntry 文件夹，可不写使用默认
 */
export async function writeContextToFileAsync(path, fileContext, dirEntry) {
	let fileEntry = await getFileEntryAsync(path);
	let file = await getFileAsync(path);
	return new Promise((resolve) => {
		fileEntry.createWriter(async writer => {
			// 写入文件成功完成的回调函数
			writer.onwrite = e => {
				resolve()
			};
			// 写入数据
			writer.write(JSON.stringify(fileContext));
		})
	});
}

// /**
//  * 判断文件是否存在
//  * @param {Object} fileName
//  * @param {Object} dirEntry
//  */
export async function checkFileExistsInDirectory(directoryEntry, fileName) {
	return new Promise((resolve, reject) => {
		const directoryReader = directoryEntry.createReader();

		directoryReader.readEntries((entries) => {
			const fileExists = entries.some(entry => entry.isFile && entry.name === fileName);
			resolve(fileExists);
		}, (error) => {
			console.error('Error reading directory entries:', error.message);
			reject(error);
		});
	});
}

/**
 * 判断文件是否存在
 * @param {string} fileName - 要判断是否存在的文件路径，例如：'archiveId_1690967987921/getModule.txt'
 * @returns {Promise<boolean>} - 返回一个 Promise，表示文件是否存在，存在为 true，不存在为 false
 */
export async function existFileAsync(fileName) {
	return new Promise((resolve) => {
		plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
			const filePath = fileName.split('/');
			let currentEntry = fs.root;

			const checkFileRecursively = async (index) => {
				return new Promise((resolve) => {
					if (index >= filePath.length) {
						resolve(true); // 已经遍历完所有路径，文件存在
						return;
					}

					let directoryReader = currentEntry.createReader();
					directoryReader.readEntries(async (entries) => {
						let found = false;
						for (let entry of entries) {
							if (entry.isDirectory && entry.name ===
								filePath[index]) {
								// 如果是目录，且名称匹配，进入下一层级目录
								currentEntry = entry;
								found = true;
								break;
							} else if (entry.isFile && entry.name ===
								filePath[index]) {
								// 如果是文件，且名称匹配，文件存在
								resolve(true);
								return;
							}
						}

						if (found) {
							// 递归进入下一层级目录
							checkFileRecursively(index + 1).then((
								isExist) => {
								resolve(isExist);
							});
						} else {
							resolve(false);
						}
					});
				});
			};

			checkFileRecursively(0).then((isExist) => {
				resolve(isExist);
			});
		});
	});
}



/**
 * 遍历dirEntry，深层次的目录暂不考虑
 * @param {Object} dirEntry
 */
export async function iterateDierctory(dirEntry) {
	return new Promise((resolve) => {
		plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
			let entry = dirEntry || fs.root;
			let directoryReader = entry.createReader();
			directoryReader.readEntries(function(entries) {
				resolve(entries);
			}, function(e) {
				console.log("Read entries failed: " + e.message);
			});
		});
	})
}